package com.lc.index.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class ControllerLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);

    // 拦截所有 Controller 方法
    @Pointcut("execution(* com.lc.index.controller..*.*(..))")
    public void controllerPointcut() {}

    @Around("controllerPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录请求信息
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        logger.info("请求入口: {}.{}, 参数: {}", className, methodName, Arrays.toString(args));

        long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = joinPoint.proceed();
            long cost = System.currentTimeMillis() - startTime;
            logger.info("请求成功: {}.{}, 耗时: {}ms", className, methodName, cost);
            return result;
        } catch (Exception ex) {
            logger.error("请求异常: {}.{}, 异常信息: {}", className, methodName, ex.getMessage(), ex);
            throw ex;
        }
    }
}